package com.chang.dp.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chang.dp.entity.UsersEntity;
import com.chang.dp.enumns.ErrorCodeEnums;
import com.chang.dp.mappers.UsersMapper;
import com.chang.dp.utils.QueryUtil;
import com.chang.dp.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jim.core.packets.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

@RestController
@Api(tags = "用户模块")
@RequestMapping(path = "/users")
public class UsersController {
    public static final Logger logger = LoggerFactory.getLogger(UsersController.class);

    @Resource
    RedisTemplate redisTemplate;
    @Autowired
    UsersMapper usersMapper;

    @ApiOperation(value = "分页获取用户列表")
    @RequestMapping(method = RequestMethod.POST, path = "/list")
    public HashMap getUserList(@RequestBody UsersEntity usersEntity) {
        QueryWrapper queryWrapper = new QueryWrapper<>(usersEntity);
        QueryUtil.dealPageListQueryWrapperTime(queryWrapper, usersEntity);
//        Page<UsersEntity> page = Page.of(1, 2);

        Page<UsersEntity> pageDTO1 = usersMapper.selectPage(usersEntity.getPagination(), queryWrapper);

        HashMap hashMap = new HashMap();
        hashMap.put("data", pageDTO1);
        hashMap.put("code", 200);
        hashMap.put("message", "OK");
        return hashMap;
    }

    @ApiOperation("新建用户")
    @RequestMapping(path = "/create", method = RequestMethod.POST)
    public HashMap createUser(@RequestBody UsersEntity usersEntity) {
        usersEntity.setUserId(StringUtil.getRandomString());
        HashMap result = new HashMap();
        int rows = usersMapper.insert(usersEntity);
        result.put("code", 200);
        result.put("success", rows == 1);
        result.put("data", usersEntity.getUserId());

        return result;
    }

    @ApiOperation("编辑用户信息")
    @RequestMapping(path = "/update", method = RequestMethod.POST)
    public HashMap updateUser(@RequestBody UsersEntity usersEntity) {
        HashMap result = new HashMap();
        int rows = usersMapper.updateById(usersEntity);
        result.put("code", 200);
        result.put("success", rows == 1);
        result.put("message", "操作成功");

        return result;
    }

    @ApiOperation("登录")
    @RequestMapping(path = "/login", method = RequestMethod.POST)
    public HashMap<String, Object> login(@RequestBody UsersEntity usersEntity) {
        HashMap<String, Object> hashMap = new HashMap<>();
        UsersEntity usersEntity1 = usersMapper.selectOne(new QueryWrapper<UsersEntity>(usersEntity));
        if (usersEntity1 == null) {
            hashMap.put("code", ErrorCodeEnums.NOT_FOUNT);
            hashMap.put("message", "账号或密码错误");
            return hashMap;
        }
        String token = StringUtil.getRandomString();
        hashMap.put("code", ErrorCodeEnums.SUCCESS);
        hashMap.put("message", "登录成功");
        hashMap.put("data", token);


        Timer timer = new Timer();

        // 将token 和用户id缓存到redis里
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String userStr = JSONObject.toJSONString(usersEntity1);
        valueOperations.set(token, userStr);
        logger.info("token " + token + "设置成功!");
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                redisTemplate.delete(token);
                logger.info("token " + token + "删除成功");
            }
        }, 1000 * 3600 * 168); // 延迟7天;
        return hashMap;
    }

    @ApiOperation("根据token查询用户详细信息")
    @RequestMapping(path = "detail", method = RequestMethod.GET)
    public HashMap<String, Object> getUserDetailByToken(@RequestHeader Map<String, String> headers) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String token = headers.get("token");
        HashMap<String, Object> result = new HashMap<>();
        Object userStr = valueOperations.get(token);

        if (userStr == null || "".equals(userStr)) {
            // 登录过期
            result.put("code", ErrorCodeEnums.AUTH_LATE);
            result.put("message", "登录过期,请重新登录");
            logger.info("根据token: " + token + " 获取用户信息失败");
        } else {
            User usersEntity = JSONObject.parseObject(userStr.toString(), User.class);
            result.put("code", ErrorCodeEnums.SUCCESS);
            result.put("message", "查询成功");
            result.put("data", usersEntity);
            logger.info("根据token: " + token + "获取用户信息成功!");
        }

        return result;
    }
}
